<?php
/**
 * 配置类
 *
 * @Author 王衍生 50634235@qq.com
 */
class base_static_config
{
    static protected $environment = 'production';

    static protected $_items = [];

    static protected $_loaded = [];

    static public function get_path()
    {
        return ROOT_DIR . '/config';
    }

    /**
     * 解析参数key
     *
     * @param [type] $key
     * @return void
     * @Author 王衍生 50634235@qq.com
     */
    static private function parse_key($key)
    {
        $segments = explode('.', $key);
        $group = $segments[0];
        if (count($segments) == 1) {
            return [$group, null];
        } else {
            $item = implode('.', array_splice($segments, 1));
            return [$group, $item];
        }
    }

    /**
     * 设置配置值
     *
     * @param [type] $key
     * @param [type] $value
     * @return void
     * @Author 王衍生 50634235@qq.com
     */
    static public function set($key, $value)
    {
        list($group, $item) = static::parse_key($key);
        static::load($group);
        if (is_null($item)) {
            static::$_items[$group] = $value;
        } else {
            array_set(static::$_items[$group], $item, $value);
        }
    }

    /**
     * 取得配置值
     *
     * @param [type] $key
     * @param [type] $default
     * @return void
     * @Author 王衍生 50634235@qq.com
     */
    static public function get($key, $default = null)
    {
        list($group, $item) = static::parse_key($key);
        static::load($group);
        return array_get(static::$_items[$group], $item, $default);
    }

    /**
     * 加载配置参数
     *
     * @param [type] $group
     * @return void
     * @Author 王衍生 50634235@qq.com
     */
    static private function load($group)
    {
        if(isset(static::$_loaded[$group]) && (static::$_loaded[$group] === true)) {
            return;
        }

        $items = static::realLoad($group);
        static::$_items[$group] = $items;
        static::$_loaded[$group] = true;
    }

    /**
     * 加载相关配置文件
     *
     * @param [type] $group
     * @return void
     * @Author 王衍生 50634235@qq.com
     */
    static private function realLoad($group)
    {
        $items = [];
        $path = static::get_path();
        if(empty($path)) {
            return $items;
        }

        $files = kernel::single('base_filesystem');

        $file = "{$path}/{$group}.php";

        if($files->exists($file)) {
            $items = $files->getRequire($file);
        }

        $env = static::$environment;

        $file = "{$path}/{$env}/{$group}.php";

		if ($files->exists($file))
		{
			$items = array_replace_recursive($items, $files->getRequire($file));
		}
        return $items;
    }
}